#include "BinaryFileHelper.h"


BinaryFileHelper::BinaryFileHelper(const char* fileName, ios_base::openmode openMode)
{
	fileStream = new fstream(fileName, openMode);
	closed = false;
}

BinaryFileHelper::~BinaryFileHelper()
{
	if (!closed)
	{
		fileStream->flush();
		fileStream->close();
	}

	delete fileStream;
}

__CLR_OR_THIS_CALL BinaryFileHelper::operator void *() const
{
	return (fileStream->fail() ? 0 : (void *)this);
}

bool __CLR_OR_THIS_CALL BinaryFileHelper::operator!() const
{
	return (fileStream->fail());
}

void BinaryFileHelper::Write(const char* data, streamsize size)
{
	fileStream->write((char*)&size, sizeof(size));
	fileStream->write(data, size);
}


void BinaryFileHelper::WriteString(tstring str)
{
	streamsize size = str.size() * sizeof(TCHAR) + sizeof(TCHAR);

	fileStream->write((char*)&size, sizeof(size));
	fileStream->write((char*)&str.c_str()[0], size);
}

tstring BinaryFileHelper::ReadString()
{
	streamsize size = 0;
	fileStream->read((char*)&size, sizeof(size));

	TCHAR* tmp = new TCHAR[size / sizeof(TCHAR)];
	fileStream->read((char*)tmp, size);

	tstring str(tmp);
	delete[] tmp;

	return str;
}

void BinaryFileHelper::Read(char* data, streamsize size)
{
	streamsize sizeFromFile = 0;
	fileStream->read((char*)&sizeFromFile, sizeof(sizeFromFile));

	if (sizeFromFile > size)
	{
		fileStream->read(data, size);
		fileStream->seekg(sizeFromFile - size, ios::cur);
	}
	else
	{
		fileStream->read(data, sizeFromFile);
	}
}

void BinaryFileHelper::Flush()
{
	fileStream->flush();
}

void BinaryFileHelper::Close()
{
	fileStream->close();
	closed = true;
}

void BinaryFileHelper::Exceptions(ios_base::iostate newExceptions)
{
	fileStream->exceptions(newExceptions);
}
